import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, InputNumber, FormInstance, Radio, DatePicker, Form, Modal, Popconfirm } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  getOrderRentList,
  getOrderRentListByAdmission,
  hangRent,
  rent,
  managerCancel
} from '@/services/order/api';
import { PlusOutlined } from '@ant-design/icons';
import {
  currentDate,
  formatDate,
  getCache,
  getDateValue,
  isNull,
  MsgType,
  parseDate,
  setCache,
  showMsg,
  isSupportSticky
} from '@/utils/utils';
import { ProFormFieldSet } from '@ant-design/pro-form';
import Detail from './Detail';
import { useModel, history } from 'umi';
import RentDialog from './RentDialog';
import './style.less';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import ChoicePatient from '@/components/ChoicePatient/list';
import FeeDetail from './FeeDetail';

interface OrderRentListProps {
  location?: any;
}

const OrderRentList: React.FC<OrderRentListProps> = (props) => {
  const { location } = props;
  const { query } = location;
  const { initialState } = useModel('@@initialState');
  const formRef = useRef<FormInstance>();
  // 查看类型
  const [radioValue, setRadioValue] = useState<number>(1);
  const [inputNo, setInputNo] = useState(''); // 身份证/病案号
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色
  const actionRef = useRef<ActionType>();
  const [visible, setVisible] = useState<boolean>(false);
  const [feeDetailVisible, setFeeDetailVisible] = useState<boolean>(false);
  const [printNow, setPrintNow] = useState<boolean>(false);

  const [currentRow, setCurrentRow] = useState<ORDERAPI.OrderRentItem>({});
  const [dialogVisible, setDialogVisible] = useState<boolean>(false);
  const [title, setTitle] = useState<string>('');
  const [params, setParams] = useState<any>({});
  const [rentType, setRentType] = useState<number>(1);
  const [rentOrderId, setRentOrderId] = useState<string>('');
  const { confirm } = Modal;
  // 现结租赁数据
  const [orderRentData, setOrderRentData] = useState<any>();
  const [cancelLoading, setCancelLoading] = useState<boolean>(false);
  const [line, setLine] = useState<number>(-1);

  const cancelCurOrder = async(entity, index, callback) => {
    setCancelLoading(true);
    setLine(index);
    if (entity.manager_flag === 'Y') {
      await managerCancel(entity.manager_order_id).then(res => {
        setLine(-1);
        setCancelLoading(false);
        showMsg('已取消结算', 'success');
        actionRef.current?.reload();
        callback?.()
      }).catch(error => {
        setLine(-1);
        showMsg(error?.data?.errmsg)
      });
    }
  }


  const columns: ProColumns<ORDERAPI.OrderRentItem>[] = [
    {
      title: '租赁登记日期',
      dataIndex: 'rent_date',
      hideInTable: true,
      order: 6,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        return (
          <ProFormFieldSet>
            <DatePicker allowClear={false} style={{ width: '100%' }} />
            <span style={{ padding: '0 5px' }}>-</span>
            <DatePicker allowClear={false} style={{ width: '100%' }} />
          </ProFormFieldSet>
        );
      },
    },
    {
      title: '病区',
      dataIndex: 'ward',
      hideInTable: true,
      order: 5,
      renderFormItem: () => {
        return (
          <Form.Item>
            <span>{initialState?.currentUser?.ward_name}</span>
          </Form.Item>
        );
      },
    },
    {
      title: '床位号',
      dataIndex: 'bed_no',
      search: false,
      width: 80,
    },
    {
      title: '患者姓名',
      dataIndex: 'patient_name',
      width: 80,
      order: 3,
      fieldProps: {
        placeholder: '输入患者姓名',
      }
    },
    // {
    //   title: '住院号',
    //   dataIndex: 'admission_num',
    //   width: 80,
    //   order: 4,
    //   fieldProps: {
    //     placeholder: '输入住院号',
    //   }
    // },
    {
      title: '身份证/病案号',
      dataIndex: 'input_no',
      order: 4,
      hideInTable: true,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <ChoicePatient
            caseNoKey={initialState?.canAll ? 'out_case_no' : 'case_no'}
            showMore
            onChoice={(e) => setInputNo(e.visit_no)}
          />
        );
      },
    },
    {
      title: '患者状态',
      dataIndex: 'admission_status',
      hideInTable: true,
      valueType: 'select',
      order: 2,
      valueEnum: {
        I: '住院中',
        O: '已出院',
      },
    },
    {
      title: '待结算金额',
      dataIndex: 'wait_price',
      hideInTable: true,
      order: 1,
      renderFormItem: () => {
        return (
          <ProFormFieldSet>
            <InputNumber style={{ width: '100%' }} placeholder="最小值" />
            <span style={{ padding: '0 5px' }}>-</span>
            <InputNumber style={{ width: '100%' }} placeholder="最大值" />
          </ProFormFieldSet>
        );
      },
    },
    {
      title: '物品名称',
      dataIndex: 'goods_name_list',
      width: 150,
      search: false,
      hideInTable: radioValue === 2,
      renderText: (_, record) => {
        return isNull(_) ? '（无）' :  _.length > 1 ? `${_[0]}（等）` : _[0];
      },
    },
    {
      title: '租赁登记日期',
      dataIndex: 'register_time',
      search: false,
      width: 180,
      hideInTable: radioValue === 2,
      renderText: (dom, entity) => {
        return `${entity.create_date} ${entity.create_time}`;
      },
    },
    {
      title: '数量',
      dataIndex: 'total_goods_num',
      search: false,
      align: 'right',
      hideInTable: radioValue === 2,
      width: 70,
    },
    {
      title: '价格',
      dataIndex: 'total_price',
      valueType: 'money',
      align: 'right',
      search: false,
      hideInTable: radioValue === 2,
      width: 100,
    },
    {
      title: '租赁状态',
      dataIndex: 'status',
      valueType: 'select',
      width: 60,
      hideInTable: radioValue === 2,
      valueEnum: {
        N: '正常',
        D: '作废',
      },
      search: false,
    },
    {
      title: '结算状态',
      dataIndex: 'sett_status',
      valueType: 'select',
      width: 90,
      hideInTable: radioValue === 2,
      valueEnum: {
        U: '未结算',
        W: '待结算',
        P: '已结算',
        G: '结算中',
      },
      search: false,
      render: (val, record) => {
        if (record.status === 'D') {
          return '-';
        }
        return val;
      }
    },
    {
      title: '租赁单数',
      dataIndex: 'rent_num',
      align: 'right',
      hideInTable: radioValue === 1,
      search: false,
    },
    {
      title: '已出账金额',
      dataIndex: 'total_rent_price',
      valueType: 'money',
      align: 'right',
      hideInTable: radioValue === 1,
      search: false,
    },
    {
      title: '已结算金额',
      dataIndex: 'total_sett_suc_price',
      valueType: 'money',
      align: 'right',
      hideInTable: radioValue === 1,
      search: false,
    },
    {
      title: '待结算金额',
      dataIndex: 'total_sett_wait_price',
      valueType: 'money',
      align: 'right',
      hideInTable: radioValue === 1,
      search: false,
    },
    {
      title: '患者状态',
      dataIndex: 'admission_status',
      search: false,
      hideInTable: radioValue === 1,
      valueType: 'select',
      valueEnum: {
        I: '住院中',
        O: '已出院',
      },
    },
    {
      title: '操作',
      align: 'center',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      width: 120,
      valueType: 'option',
      render: (_, record, index) => [
        (radioValue === 1) ? (
          <div>
          <PermissionControl key="view" action_id="400402004">
            <a
              onClick={() => {
                setVisible(true);
                setCurrentRow(record);
              }}
            >
              查看
            </a>
          </PermissionControl>
          {
            record.manager_flag === 'Y' &&
            <Popconfirm
              placement="topRight"
              key="cancel"
              title={'该笔订单已经通过出院办结发起结算，是否确认取消？'}
              onConfirm={async () => cancelCurOrder(record, index)}
              okText="确认取消"
              cancelText="再想想">
              <Button
                loading={cancelLoading && line === index}
                type="link">取消</Button>
              </Popconfirm>
          }
          </div>
        ) : radioValue === 2 && (
          <PermissionControl key="view" action_id="400402005">
            <a
              onClick={() => {
                history.push({
                  pathname: '/order/rent/settlement',
                  query: {
                    admission_num: record.admission_num as string,
                    type: 'edit',
                  },
                });
              }}
            >
              查看/结算
            </a>
          </PermissionControl>
        ),
      ],
    },
  ];
  
  /**
   *
   * @param values
   */
  const handleRent = async (values: any) => {
    try {
      if (rentType === 1) {
        await hangRent(values);
        return true;
      }
      // 现结租赁
      const data = await rent(values);
      return data;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  };

  // 支付后回调
  const optCallback = (data: any) => {
    setVisible(false);
    setDialogVisible(false);

    // 提交支付
    const orderSumbitConfig = {
      title: '',
      content: `订单提交成功，请在【${data?.pay_valid_time}】前完成缴费`,
      cancelText: '知道了',
      okText: data?.rentType === 2 ? '打印支付单' : '打印结算单',
      onOk() {
        console.log('OK', data);
        if (data?.rentType === 2) {
          console.log(data);
          setRentOrderId(data.rent_order_id);
          setFeeDetailVisible(true);
          setPrintNow(true);
        } else {
          setVisible(true);
          setPrintNow(true);
        }
      },
      onCancel() {
        console.log('onCancel', data);
        if (data?.rentType === 2) {
          setCurrentRow(data);
        }
        setVisible(true);
        actionRef.current?.reload();
      },
    };
    confirm(orderSumbitConfig);
    actionRef.current?.reload();
  };

  // 现结租赁提交支付
  const orderRentSubmitPay = (data: any) => {
    setVisible(true);
    setOrderRentData(data);
    setCurrentRow({});
  };

  useEffect(() => {
    if (query?.from !== 'detail') {
      formRef.current?.setFieldsValue({
        rent_date: [currentDate(), '', currentDate()],
      });
      formRef.current?.submit();
      return;
    }
    const type = Number(query?.type);
    // 设置选中的单选按钮
    setRadioValue(type);
    setParams({
      type,
    });
    setClickRow(query?.admission_num);

    if (type === 1) {
      formRef.current?.setFieldsValue({
        rent_date: [currentDate(), '', currentDate()],
      });
      formRef.current?.submit();
      return;
    }

    let searchCondition = getCache('rent_order');
    searchCondition = JSON.parse(searchCondition || '{}');

    formRef.current?.setFieldsValue({
      rent_date: [
        searchCondition.begin_create_date
          ? parseDate(searchCondition.begin_create_date)
          : currentDate(),
        '',
        searchCondition.end_create_date
          ? parseDate(searchCondition.end_create_date)
          : currentDate(),
      ],
      admission_num: searchCondition.admission_num,
      patient_name: searchCondition.patient_name,
    });
    formRef.current?.submit();
  }, []);

  return (
    <PageContainer extra={[<BreadcrumbDept />]} className="rent-container" breadcrumb={{}}>
      <ProTable<
        ORDERAPI.OrderRentItem,
        ORDERAPI.OrderRentItem & { rent_date: any[]; wait_price: any[] } & COMMON.PageParams
      >
        // rowKey={radioValue === 1 ? "rent_order_id" : 'admission_num'}
        rowKey={(record) => record.rent_order_id || record.admission_num}
        actionRef={actionRef}
        formRef={formRef}
        bordered
        manualRequest={true}
        params={params}
        request={async (params) => {
          console.log(params);
          params['ward'] = initialState?.currentUser?.ward_name;
          const { rent_date, wait_price } = params;
          const extra = {
            begin_create_date: '',
            end_create_date: '',
            max_sett_price: '',
            min_sett_price: '',
          };
          if (rent_date && rent_date.length) {
            extra.begin_create_date = rent_date[0] && formatDate(rent_date[0], 'YYYYMMDD');
            extra.end_create_date = rent_date[2] && formatDate(rent_date[2], 'YYYYMMDD');
            // @ts-ignore
            delete params.rent_date;
          }
          if (wait_price && wait_price.length) {
            extra.min_sett_price = wait_price[0];
            extra.max_sett_price = wait_price[2];
            // @ts-ignore
            delete params.wait_price;
          }
          if (inputNo.length >= 15) {
            extra.identity_no = inputNo;
            extra.admission_num = '';
          } else {
            extra.identity_no = '';
            extra.admission_num = inputNo;
          }

          params = { ...params, ...extra };
          // @ts-ignore
          delete params.type;

          for (const prop in params) {
            if (!params[prop]) {
              delete params[prop];
            }
          }

          // 日期对比
          if (rent_date && rent_date[0] && rent_date[2]) {
            if (getDateValue(rent_date[0]) > getDateValue(rent_date[2])) {
              showMsg('租赁登记结束日期不能早于开始日期', MsgType.INFO);
              return {
                data: [],
                success: true,
                total: 0,
              };
            }
          }

          if (wait_price) {
            if (wait_price[0] && wait_price[0] < 0) {
              showMsg('金额不能小于0', MsgType.INFO);
              return {
                data: [],
                success: true,
                total: 0,
              };
            }

            if (wait_price[2] && wait_price[2] < 0) {
              showMsg('金额不能小于0', MsgType.INFO);
              return {
                data: [],
                success: true,
                total: 0,
              };
            }
          }

          if (wait_price && wait_price[0] && wait_price[2]) {
            if (wait_price[0] > wait_price[2]) {
              showMsg('待结算金额最大值不能小于最小值', MsgType.INFO);
              return {
                data: [],
                success: true,
                total: 0,
              };
            }
          }

          // 住院号查询，缓存查询条件
          if (radioValue === 2) {
            const searchCondition = {};
            for (const prop in params) {
              if (!['current', 'pageSize'].includes(prop)) {
                searchCondition[prop] = params[prop];
              }
            }
            setCache('rent_order', JSON.stringify(searchCondition));
          }

          try {
            const data: ORDERAPI.OrderRentItemList =
              radioValue === 1
                ? await getOrderRentList(params)
                : await getOrderRentListByAdmission(params);
            const list = data.record_list.map((item, index) => {
              return {
                ...item,
                index,
              };
            });
            return {
              data: list,
              success: true,
              total: data.sum_record_num,
            };
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0,
            };
          }
        }}
        className="rent-table"
        search={{
          labelWidth: 100,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [
              <PermissionControl key="search" action_id="400402000">
                {dom}
              </PermissionControl>,
            ];
          },
        }}
        options={false}
        toolbar={{
          menu: {
            items: [
              {
                key: 'hang',
                label: (
                  <PermissionControl action_id="400402001">
                    <Button
                      onClick={() => {
                        setDialogVisible(true);
                        setTitle('挂帐租赁登记');
                        setRentType(1);
                      }}
                      icon={<PlusOutlined />}
                      type="primary"
                    >
                      挂帐租赁
                    </Button>
                  </PermissionControl>
                ),
              },
              {
                key: 'add',
                label: (
                  <PermissionControl action_id="400402002">
                    <Button
                      onClick={() => {
                        setDialogVisible(true);
                        setTitle('现结租赁登记');
                        setRentType(2);
                      }}
                      icon={<PlusOutlined />}
                      type="primary"
                    >
                      现结租赁
                    </Button>
                  </PermissionControl>
                ),
              },
            ],
          },
        }}
        columns={columns}
        pagination={{
          showQuickJumper: true,
        }}
        toolBarRender={() => {
          return [
            <Radio.Group
              value={radioValue}
              onChange={(e: any) => {
                const value = e.target.value;
                setClickRow('');
                setRadioValue(value);
                setParams({
                  type: value,
                });
              }}
            >
              <Radio value={1}>按单据展示</Radio>
              <Radio value={2}>按住院号展示</Radio>
            </Radio.Group>,
          ];
        }}
        scroll={{
          x: 1000,
        }}
        onRow={record => {
          return {
            onClick: event => { setClickRow(radioValue === 1 ? record.rent_order_id : record.admission_num) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return (radioValue === 1 ? record.rent_order_id : record.admission_num) === clickRow ? 'tableRowClick' : ''
        }}
      />

      {visible && (
        <Detail
          handleModalVisible={(vis: boolean) => {
            setVisible(vis);
            actionRef.current?.reload();
          }}
          optCallback={optCallback}
          handleRent={handleRent}
          rentType={rentType}
          orderRentData={orderRentData}
          record={currentRow}
          printNow={printNow}
          setPrintNow={setPrintNow}
          cancelOrder={(callback) => {
            cancelCurOrder(currentRow, line, callback);
          }}
        />
      )}

      {dialogVisible && (
        <RentDialog
          title={title}
          rentType={rentType}
          actionRef={actionRef}
          handleRent={handleRent}
          optCallback={orderRentSubmitPay}
          handleModalVisible={setDialogVisible}
        />
      )}

      {feeDetailVisible && (
        <FeeDetail printNow={printNow} setPrintNow={setPrintNow} handleModalVisible={setFeeDetailVisible} rent_order_id={rentOrderId} />
      )}
    </PageContainer>
  );
};
export default OrderRentList;
